/*
 * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AllocateAddressResult;
import com.amazonaws.services.ec2.model.AssociateAddressRequest;
import com.amazonaws.services.ec2.model.AttachVolumeRequest;
import com.amazonaws.services.ec2.model.CreateImageRequest;
import com.amazonaws.services.ec2.model.CreateImageResult;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.CreateVolumeRequest;
import com.amazonaws.services.ec2.model.CreateVolumeResult;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DetachVolumeRequest;
import com.amazonaws.services.ec2.model.Placement;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;


public class AwsConsoleApp {



    static AmazonEC2      ec2;
    static AmazonS3       s3;

    /**
     * The only information needed to create a client are security credentials
     * consisting of the AWS Access Key ID and Secret Access Key. All other
     * configuration, such as the service endpoints, are performed
     * automatically. Client parameters, such as proxies, can be specified in an
     * optional ClientConfiguration object when constructing a client.
     *
     * @see com.amazonaws.auth.BasicAWSCredentials
     * @see com.amazonaws.auth.PropertiesCredentials
     * @see com.amazonaws.ClientConfiguration
     */
    private static void init() throws Exception {
        AWSCredentials credentials = new PropertiesCredentials(
                AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties"));

        ec2 = new AmazonEC2Client(credentials);
        s3  = new AmazonS3Client(credentials);
    }


    public static void main(String[] args) throws Exception {

        System.out.println("===========================================");
        System.out.println("Welcome to the AWS Java SDK!");
        System.out.println("===========================================");

        init();

        /*
         * Amazon EC2
         */
        try {
        	System.out.println("Create Instances");
            String imageId = "ami-a2a703cb"; //Amazon Linux AMI 2012.03 64-bit  ami-e565ba8c
            int minInstanceCount = 1; // create 1 instance
            int maxInstanceCount = 1;
            RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
            Placement place = new Placement("us-east-1c");
            rir.setMonitoring(true);
            rir.withKeyName("MyKey");
            rir.withSecurityGroups("MyGroup");
            rir.withInstanceType("t1.micro");
            rir.withPlacement(place);
            RunInstancesResult result = ec2.runInstances(rir);
                        
            String ins1 = null;
            //String ins2 = null;
            ins1 = result.getReservation().getInstances().get(0).getInstanceId();
            //ins2 = result.getReservation().getInstances().get(1).getInstanceId();
            
//            CreateTagsRequest ctr = new CreateTagsRequest();
//            ctr.withResources(ins1).withTags(new Tag("Name","Head node"));
//            ec2.createTags(ctr);
            
            System.out.println("Wait for 40 seconds...");
            Thread.sleep(40000);
            DescribeInstancesRequest dir = new DescribeInstancesRequest();
            dir.withInstanceIds(ins1);
            DescribeInstancesResult diresult = ec2.describeInstances(dir);
            System.out.println("IP: "+diresult.getReservations().get(0).getInstances().get(0).getPublicIpAddress());
//            System.out.println("Allocate elastic IP addresses.");
//            String ip[] = new String[10];
//            for(int i=0;i<10;i++) {
//            	AllocateAddressResult elasticResult = ec2.allocateAddress();
//            	ip[i] = elasticResult.getPublicIp();
//            }
			//ec2.associateAddress(new AssociateAddressRequest(ins1,ip1));
            
			System.out.println("Configure client. When u finish, type in anything and press Enter key");
			Scanner input = new Scanner(System.in);
			String a = input.next();
			
            System.out.println("Create image.");
            CreateImageResult cir1 = ec2.createImage(new CreateImageRequest(ins1,ins1));
            String imageId1 = cir1.getImageId();
//            CreateImageResult cir2 = ec2.createImage(new CreateImageRequest(ins2,ins2));
//            String imageId2 = cir2.getImageId();
                        
            System.out.println("Store configuration in s3.");
            String bucketName = "wangzitong";
            s3.createBucket(bucketName);
            String key = "client";
            
            //s3.deleteObject(bucketName, key1);
            //s3.deleteObject(bucketName, key2);
            
//            File file1 = File.createTempFile(key1, ".txt");
//            file1.deleteOnExit();
//            Writer wr = new OutputStreamWriter(new FileOutputStream(file1));
//            wr.write(imageId1+"\r\n"+ip1+"\r\n");
//            wr.close();            
//            s3.putObject(bucketName, key1, file1);
            
            File file = File.createTempFile(key, ".txt");
            file.deleteOnExit();
            Writer wr = new OutputStreamWriter(new FileOutputStream(file));
            wr.write(imageId1+"\r\n");
            wr.close();            
            s3.putObject(bucketName, key, file);
            
            System.out.println("Wait for 60 seconds...");
            Thread.sleep(60000);
            System.out.println("Terminate instances.");
            List<String> instanceIds = new LinkedList<String>();
            instanceIds.add(ins1);
            //instanceIds.add(ins2);
            ec2.terminateInstances(new TerminateInstancesRequest(instanceIds));
            
            System.out.println("Finished!");
            ec2.shutdown();
            //s3.shutdown();
        } catch (AmazonServiceException ase) {
                System.out.println("Caught Exception: " + ase.getMessage());
                System.out.println("Reponse Status Code: " + ase.getStatusCode());
                System.out.println("Error Code: " + ase.getErrorCode());
                System.out.println("Request ID: " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            /*
             * AmazonClientExceptions represent an error that occurred inside
             * the client on the local host, either while trying to send the
             * request to AWS or interpret the response. For example, if no
             * network connection is available, the client won't be able to
             * connect to AWS to execute a request and will throw an
             * AmazonClientException.
             */
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}
